/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ucuenca.ec.nosql.conexion;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import edu.ucuenca.ec.nosql.modelos.Producto;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *
 * @author mivkys
 */
public class CassandraConnector {

    private static Cluster cluster;
    private static Session session;

    public static void connect(final String node, final int port) {
        cluster = Cluster.builder().addContactPoint(node).withPort(port).build();
        final Metadata metadata = cluster.getMetadata();
        System.out.printf("Connected to cluster: %s\n", metadata.getClusterName());
        for (final Host host : metadata.getAllHosts()) {
            System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n",
                    host.getDatacenter(), host.getAddress(), host.getRack());
        }
        session = cluster.connect();
    }

    public Session getSession() {
        return this.session;
    }

    public static void close() {
        cluster.close();
    }

    public static void insertarRelacion(final int idCliente, final int idProducto) {
        session.execute("INSERT INTO relacion_cliente_producto (idCliente, idProducto) "
                + "VALUES (?, ?, ?, ?, ?)",
                idCliente, idProducto);
    }

    public static List<Optional<Producto>> findProductos(final int idCliente) {
        List<Optional<Producto>> productos = new ArrayList<>();
        final ResultSet movieResults = session.execute(
                "SELECT * from relacion_cliente_producto WHERE idCliente = ?", idCliente);
        final List<Row> productoRows = movieResults.all();
        for (Row productoRow : productoRows) {
            if (productoRow != null) {
                productos.add(Optional.of(new Producto(productoRow.getInt("idProducto"))));
            }
        }
        return productos;
    }

    public void deleteRelacion(final String title, final int year) {
        final String deleteString = "DELETE FROM relacion_cliente_producto WHERE idCliente = ?";
        session.execute(deleteString, title);
    }

    public static void crearTabla() {
        final String createMovieCql = "CREATE TABLE relacion_cliente_producto (idCliente int, idProducto int, PRIMARY KEY (idCliente))";
        session.execute(createMovieCql);
    }
}
